package com.woniuxy.service.impl;

import com.woniuxy.dao.IProductDao;
import com.woniuxy.entity.Product;
import com.woniuxy.exception.StockNotEnoughException;
import com.woniuxy.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @author : mafan
 * @date : 2020-11-18 20:32
 **/
@Service
@Transactional
public class ProductServiceImpl implements IProductService {
    @Autowired
    private IProductDao productDao;

    @Override
    public Product find(Integer pid) {
        Optional<Product> optional = productDao.findById(pid);
        return optional.isPresent() ? optional.get() : null;
    }

    @Override
    public void deductStock(Integer pid, Integer number) {
        Optional<Product> optional = productDao.findById(pid);
        Product product = optional.isPresent() ? optional.get() : null;
        if (product != null) {
            if (product.getStock() < number) {
                throw new StockNotEnoughException("剩余库存："+product.getStock()+"顶单数量："+number);
            }
            product.setStock(product.getStock() - number);
        }
        productDao.save(product);
    }
}
